<template>
  <div class="app-container app-content">
    <div class="top-title">
      <span class="tinyTitle">
        <div class="titleFlag"></div>
        <!-- {{ salaryItem.title || '学历薪酬变化' }} -->
        薪酬趋势
      </span>
      <!-- type="card" -->
      <!-- <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="数据图表" name="chart"></el-tab-pane>
        <el-tab-pane label="基本数据" name="full"></el-tab-pane>
      </el-tabs> -->
    </div>
    <!-- <div class="top-line"></div> -->
    <template v-if="activeName == 'full'">
      <el-row class="search-container">
        <el-form ref="form" :model="form">
          <el-form-item label="统计时间">
            <el-date-picker
              v-model="selectBetweenTime"
              type="monthrange"
              :clearable="false"
              size="small"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              :picker-options="pickerOptions"
              @change="handleDateChange"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="学历筛选">
            <educationSearch @change="handleEducationChange" />
          </el-form-item>
          <el-form-item label="区域名称">
            <regoinSearch ref="regionRef" @onRegionChange="onRegionChange" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="fetchData()"
              >查询</el-button
            >
            <el-popover
              placement="top-start"
              width="200"
              trigger="hover"
              content="通过您的筛选条件，计算平均薪酬以及职位总数"
            >
              <el-button
                slot="reference"
                type="primary"
                plain
                @click="fetchTotalData()"
                style="margin-left: 10px"
                >计算查询结果
              </el-button>
            </el-popover>
            <!-- <el-button type="primary" @click="addGroupByColumn()" style="margin-left:10px">根据学历统计平均数据</el-button> -->
          </el-form-item>
        </el-form>
      </el-row>
      <div class="list">
        <el-tooltip effect="light" placement="top">
          <div class="toolTipGuide" slot="content">
            <div class="toolTipTitle"></div>
            <div
              class="toolTipItems"
              v-for="(item, index) in stepInfo"
              :key="index"
            >
              <div class="stepImageContainer">
                <img :src="item.stepImage" class="stepImage" />
              </div>
              <div class="stepDesc">{{ item.stepDesc }}</div>
            </div>
          </div>
          <el-button
            size="mini"
            class="filter-item"
            icon="el-icon-download"
            @click="onExportClick"
            >导出
          </el-button>
        </el-tooltip>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          @sort-change="sortChange"
        >
          <el-table-column label="区域名称">
            <template slot-scope="scope">
              {{ scope.row.salaryRegionName }}
            </template>
          </el-table-column>
          <el-table-column label="学历">
            <template slot-scope="scope">
              {{ scope.row.eduName }}
            </template>
          </el-table-column>
          <el-table-column label="平均薪酬" prop="salary_num" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.salaryNum }}
            </template>
          </el-table-column>
          <el-table-column
            label="职位数量"
            prop="company_num"
            sortable="custom"
          >
            <template slot-scope="scope">
              {{ scope.row.companyNum }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="tablePage.pageNum"
          :page-size="tablePage.pageSize"
          :page-sizes="pageSizes"
          :total="tablePage.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </template>
    <div class="echart" v-if="activeName == 'chart'">
      <div class="educationSalaryChangesChart">
        <educationSalaryChangesChart />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getEducationSalaryList,
  getEducationSalaryTotalData,
  getEducationSalaryListExport,
} from "@/api/salary";
import regoinSearch from "@/views/position/components/regoinSearch";
import educationSearch from "@/views/position/components/educationSearch";
import educationSalaryChangesChart from "./educationSalaryChangesChart";

export default {
  name: "companySalaryChanges",
  props: {
    salaryItem: {
      type: Object,
      require: true,
    },
  },
  components: {
    regoinSearch,
    educationSearch,
    educationSalaryChangesChart,
  },
  data() {
    return {
      form: {},
      list: null,
      totalData: {
        salaryNum: null,
        companyNum: null,
      },
      listLoading: true,
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      positionName: "",
      selectTime: "",
      regionId: "",
      regionList: [],
      currentRegionName: "全国",
      currentChartRegionName: "全国",
      pageSizes: [10, 20, 30],
      educationOptions: [
        { label: "全部", value: "" },
        { label: "高中及以下", value: "高中及以下" },
        { label: "大专", value: "大专" },
        { label: "本科", value: "本科" },
        { label: "硕士", value: "硕士" },
        { label: "博士", value: "博士" },
        { label: "博士及以上", value: "博士及以上" },
      ],
      educationValue: "",
      orderByColumn: "",
      groupByColumn: "edu_name",
      orderBy: "",

      selectBetweenTime: "",
      // 时间选择器
      pickerOptions: {
        shortcuts: [
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      stepInfo: [
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide1.png",
          stepDesc: "第一步，打开导出文件",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide2.png",
          stepDesc: "第二步，选择数据范围。",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide3.png",
          stepDesc: "第三步，选择全部图表",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide4.png",
          stepDesc: "第四步，选择自己需要的样式备份",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide5.png",
          stepDesc: "第五步，图表制作完成啦！",
        },
      ],
      activeName: "chart",
      chartData: [],
    };
  },
  created() {
    this.fetchData();
    this.positionName = this.$route.query.name;
  },
  methods: {
    handleClick() {
      if (this.activeName == "full") {
        this.currentRegionName = "全国";
        this.groupByColumn = "edu_name";
        this.regionList = [];
        let date = new Date();
        let currentMonth = date.getMonth() + 1;
        let value =
          date.getFullYear() +
          "-" +
          (currentMonth < 10 ? "0" : "") +
          currentMonth +
          "-" +
          "01";

        // 默认显示上月日期
        let date1 = new Date();
        date1.setMonth(date1.getMonth() - 1); // 减去一个月
        let previousMonth = date1.getMonth() + 1;
        let value1 =
          date1.getFullYear() +
          "-" +
          (previousMonth < 10 ? "0" : "") +
          previousMonth +
          "-" +
          "01";

        // 确保selectBetweenTime中的日期按照从小到大的顺序排列
        this.selectBetweenTime = [value, value1].sort();
        this.educationValue = "";
        this.fetchData();
      } else {
        this.groupByColumn = "";
      }
    },
    handleDateChange(val) {
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    handleEducationChange(val) {
      console.log("handleEducationChange--------->", val.value);  
      this.educationValue = val.value;
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onRegionChange(val) {
      //console.log("onRegionChange--------->", val.label);
      this.currentRegionName = val.label;
      this.regionList = [val.value];
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: this.tablePage.pageNum,
        perPage: this.tablePage.pageSize,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.educationValue != "") {
        params.selectValue = this.educationValue;
      }
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      if (this.groupByColumn != null && this.groupByColumn != "") {
        params.groupByColumn = this.groupByColumn;
      }
      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }

      getEducationSalaryList(params).then((response) => {
        const count = response.data.count - 0;
        this.tablePage.total = count;
        this.list = response.data.rows;
        if (this.groupByColumn != "") {
          this.list.forEach((item) => {
            item.salaryRegionName =
              this.currentRegionName != "" && this.currentRegionName != null
                ? this.currentRegionName
                : "全国";
          });
        }
        // this.groupByColumn = "";
        this.listLoading = false;
      });
    },
    fetchTotalData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      if (this.educationValue != "") {
        params.selectValue = this.educationValue;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      this.fetchData();
      getEducationSalaryTotalData(params).then((response) => {
        if (
          response.data != null &&
          response.data.companyNum != null &&
          response.data.salaryNum != null
        ) {
          this.totalData.salaryNum = parseFloat(
            response.data.salaryNum
          ).toFixed(2);
          this.totalData.companyNum = response.data.companyNum;
        } else {
          this.totalData.salaryNum = 0;
          this.totalData.companyNum = 0;
        }
        let content =
          `<div style='border-top:1px solid #e8e8e8;border-bottom:1px solid #e8e8e8;margin-top:-10px;font-size:14px;padding:28px 0;text-align:left;'>` +
          "<div style='font-size:16px;font-weight:bold;color:#222;margin-bottom:0px;'>通过您的查询条件（岗位，地区，时间）可得：</div>" +
          "<br/>" +
          "您查询的地区：[ " +
          (this.currentRegionName == "" || this.currentRegionName == null
            ? "全国"
            : this.currentRegionName) +
          " ] " +
          "<br>" +
          " 您查询的时间区间为：[ " +
          (this.selectBetweenTime == "" || this.selectBetweenTime == null
            ? "不限时间"
            : this.selectBetweenTime) +
          " ] " +
          "<br>" +
          "  平均薪酬为： " +
          this.totalData.salaryNum +
          "<br>" +
          " 职位总数为： " +
          this.totalData.companyNum;
        +`</div>`;

        this.$alert(content, "计算查询结果", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
        });
        this.listLoading = false;
      });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      this.fetchData();
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.fetchData();
      // 在此刷新数据
    },
    onExportClick() {
      // 导出方法
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: 1,
        perPage: 10000,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }
      if (this.groupByColumn != null && this.groupByColumn != "") {
        params.groupByColumn = this.groupByColumn;
        params.regionName = this.currentRegionName || "全国";
      }
      getEducationSalaryListExport(params)
        .then((result) => {
          const link = document.createElement("a"); // 创建a标签
          const blob = new Blob([result], { type: "application/vnd.ms-excel" }); // 设置文件流
          link.style.display = "none";
          // 设置连接
          link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
          link.download =
            (this.$route.query.name != undefined
              ? this.$route.query.name
              : "") + "学历薪酬数据统计表";
          document.body.appendChild(link);
          // 模拟点击事件
          link.click(); // 设置点击事件
          this.listLoading = false;
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
        })
        .catch((err) => {
          console.log(err);
        });
    },
    sortChange(column) {
      this.orderByColumn = column.prop != null ? column.prop : "salary_num";
      this.orderBy = column.order != null ? column.order : "desc";
      this.fetchData();
      // 在此刷新数据
    },
    addGroupByColumn() {
      this.groupByColumn = "edu_name";
      this.fetchData();
      // this.groupByColumn = "";
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding-top: 0px;
  overflow: hidden;
}
.app-content {
  padding-left: 0px;
}
.top-title {
  display: flex;
  margin: 20px 40px 10px 0px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #222;
  font-weight: bold;
  margin-right: 40px;

  .titleFlag {
    width: 4px;
    height: 18px;
    border-radius: 32px;
    background-color: #409eff;
    margin-right: 12px;
    color: red;
  }
}

.top-line {
  height: 1px;
  background-color: #cfd8f5;
  margin: -24px 0px 20px 180px;
}
.regionLineDesc {
  /* // margin-left: 45px; */
  display: flex;
  flex: 0.35;
  flex-wrap: wrap;
  /* width: 400px; */
  justify-content: space-between;
  /* align-content: center; */
  margin: 20px 10px 10px 10px;
}
.cityTitle {
  display: flex;
  width: 100%;
  margin: 10px auto;
  font-size: 18px;
  font-weight: bold;
  color: #222;
  align-items: center;
}
.cityTitle::before {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  top: 50%;
  border-radius: 50%;
  background-color: #24cd91;
  margin-right: 8px;
}
.regionLineDescItem {
  margin: 10px 0px;
  width: 50%;
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  /* align-items: center; */
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-500-Medium;
}
.rmb {
  font-size: 18px;
}
::v-deep .el-tabs__item {
  height: 40px !important;
  color: #555;
  font-size: 16px;
}
::v-deep .el-tabs__item.is-active {
  color: #1574ff;
  font-weight: bold;
}
::v-deep .el-tabs__nav-wrap::after {
  background-color: transparent;
  height: 1px;
}
::v-deep .el-table .el-table__body-wrapper {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep .el-table {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep.el-table .el-table__header-wrapper .el-table__header th,
::v-deep.el-table .el-table__body-wrapper tbody .el-table__row td {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
.search-container {
  /* margin-bottom: 24px; */
  /* max-width: 100vw; */
}
.pagination {
  margin-top: 24px;
}
::v-deep .el-table th > .cell {
  color: rgba(0, 0, 0, 0.85);
}
::v-deep .el-table th {
  background-color: #fafafa;
}
::v-deep.el-form--inline .el-form-item {
  margin-right: 24px;
}
.filter-item {
  margin-bottom: 12px;
}

::v-deep .el-form-item {
  display: flex;
  align-items: center;
}
::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 68px !important;
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep .el-button--primary {
  color: #fff;
  background: #0b6eff;
  border-color: #0b6eff;
}
::v-deep .el-button--primary.is-plain {
  color: #409eff;
  background: #fff;
  border-color: #b3d8ff;
}
.toolTipGuide {
  display: flex;
}
.toolTipItems {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stepImageContainer {
}
.stepImage {
  width: 264px;
  height: 149px;
}
.stepDesc {
  margin-top: 14px;
  font-size: 14px;
}
</style>
